package com.wnxy.sdd.front.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wnxy.sdd.front.entity.Course;
import com.wnxy.sdd.front.entity.Order;
import com.wnxy.sdd.front.service.ICourseService;
import com.wnxy.sdd.front.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IOrderService orderService;

    @GetMapping
    public String orderPage(String courseId, Model model) {
        // 1. 根据课程ID查询课程数据
        Course course = courseService.getById(courseId);
        // 2. 将课程数据绑定到前端页面
        model.addAttribute("course", course);
        String orderId = UUID.randomUUID().toString().replace("-", "");
        model.addAttribute("orderId", orderId);
        // 3. 返回支付页面的视图名称
        return "order";
    }


    public static final String saveURL = "https://openapi.alipaydev.com/gateway.do";
    public static final String appId = "2021000122671720";
    public static final String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCN6R8mj9J7k7GJ9lnQqdX+eTrVU6094JNz3IaSb+YB61cPXzPqpUPX+LqtpNfv34AR1U7q1DiPMk1ZMH7qCYnh8fyGINvfNn5AymPYcr4ggzY51Yl53PB2IVBlqO56ARpBNgKZj1bblkZT6Gd1Q1Cnx5x/pD3XmnUZR8N+qgZ9RvEjErf4viSI89/SHCOPvpy+66SscYRVcceTASvcxQ3VPXjFhz0GC4JZF2SAuQchn8VjcpLCjT8pc/sTQIetEGEJUo61od/T+gcBYUZ876Yg0WVy1I+IIWQCbm+0FAMBamLgLszF01A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zouPAnIECgYBmNJLX34RDCMSII9bPaV6euDhlOxv1ldbsi2WF97unXLBVkZVjNtx2XRYOK2F1w3ApRXWYFXD9Zvi1qu4JV+btU6z7BiQVspWPSWYRby3FQziP9zAutQFO/r6G6Ved7ha5ptVS2bj0GgzeqaXWR1fSB7hl4yyVkSwDXZD0JwXVRg==";
    public static final String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhvZtzCRx2AteQLpoS1MHLjhnXKYk43OvUaVhO2LErJdEeuiv4BJP3P3Thcpnf/0OqjWQ1mQYfYZNu0divD2Q5xdKOVFvmr8PNxEqbSCsQWSU2dIDIGuKTW0EkrElF3TeHmvpcrpAtPrukw+1NbjDaHfqpaDkZ+acH/GwKr6QDsX36+z9tP7o4hGp31/FZUJexAeftf5bNDBq0MuhCAW3k7T/89dsCrWTa4CZUw9ep9dR8RXF1d7vDaBzH/BqfoyHVa3gPQEkw/jg//7Vhgf+rFBt6KlStf8El8r7kN9DTwhVXIzmpvaXwgvo0F3YoVgU11jPpcLmYIEm+JNrWSvCmQIDAQAB";


    @GetMapping("/create/{courseId}")
    public void create(@PathVariable String courseId, HttpServletResponse httpResponse) {
        // 生成订单信息
        Order order = orderService.createOrder(courseId);
        // 支付

        //支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                saveURL,   // 支付宝网关（固定）。
                appId,     //APPID 即创建应用后生成。
                privateKey,//私钥
                "json",
                "UTF-8",
                alipayPublicKey, //公钥
                "RSA2");  //获得初始化的AlipayClient

        //2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://uqsse6.natappfree.cc");
        alipayRequest.setNotifyUrl("http://uqsse6.natappfree.cc/order/notify");   //在公共参数中设置回跳和通知地址

        //发送支付的信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",order.getId());                   // 订单编号
        bizContent.put("total_amount", order.getPrice());               // 金额
        bizContent.put("subject", "蜗牛精品课程");            // 订单标题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");       // 固定配置
        alipayRequest.setBizContent(bizContent.toString());

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + "UTF-8");
        try {
            httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面

            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/notify")
    @ResponseBody
    public String notify_url(HttpServletRequest request) throws AlipayApiException {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                System.out.println(name + " = " + request.getParameter(name));
            }
            //可以查看 params 中的参数 信息
            String outTradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
                Order order = orderService.getById(outTradeNo);
                //修改订单
                if (order != null) {
                    order.setTradeNo(alipayTradeNo);  //交易号
                    order.setPayTime(new Date());     //付款时间
                    order.setStatus("2");             //付款状态
                    orderService.updateById(order);    //更新订单
                }
            }
        }
        return "success";
    }
}